<?php
/**
 * Created by PhpStorm.
 * User: chenguangpeng
 * Date: 15-7-22
 * Time: 上午9:24
 * 票付通资源库
 */

namespace PFT\Resource;


class PftResource {

    private $db;

    public function __construct(\PDO $db=null)
    {
        $this->db = $db;
    }

    public function CountProduct()
    {
        $sql  = "SELECT COUNT(*) AS cnt,p_type FROM pft_resource GROUP BY p_type";
        $stmt = $this->db->prepare($sql);
        $data = array(
            'A'=>0,'B'=>0,'C'=>0,'D'=>0
        );

        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            $data[$row['p_type']] = $row['cnt'];
        }
        return $data;
    }

    public function show(Array $params, $getTotal=false, $offset=0, $limit=10)
    {
        $where = '1=1';
        $search = array();
        array_walk($params, function($val, $key) use (&$where, &$search) {
            $where      .= " AND $key=?";
            $search[]    = $val;
        });
        if ($getTotal===true) {
            $sql = "SELECT COUNT(*) FROM pft_resource WHERE $where";
            $stmt = $this->db->prepare($sql);
            $stmt->execute($search);
            return $stmt->fetchColumn(0);
        }
        $sql = "SELECT * FROM pft_resource WHERE $where LIMIT $offset, $limit";
        $stmt = $this->db->prepare($sql);
        $stmt->execute($search);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * 保存资源信息
     *
     * @return array|bool
     */
    public function SaveResource()
    {
        $update_id = intval($_POST['update_id']);
        $where = '';
        if ($update_id) {
            $where = " AND id <> $update_id";
        }
        //检测是否存在相同的产品名称
        $title = safetxt($_POST['title']);
        $strChkTitle = "SELECT id FROM pft_resource WHERE title='$title' $where LIMIT 1";
        $stmt = $this->db->prepare($strChkTitle);
        $stmt->execute();
        if ($stmt->fetchColumn(0)) {
            return array('status'=>'fail', 'msg'=>"资源【{$title}】已存在");
        }
        $p_type = safetxt($_POST['p_type']);
        $tel    = safetxt($_POST['tel']);
        $jtype  = safetxt($_POST['jtype']);
        $address= safetxt($_POST['address']);
        $runtime= safetxt($_POST['runtime']);
        $jtzn   = safehtml($_POST['jtzn']);
        $jdjj   = safehtml($_POST['jdjj']);
        $bhjq   = safehtml($_POST['bhjq']);
        $jqts   = safehtml($_POST['jqts']);
        $verify_status   = $_SESSION['sid']==1 ? 1 : 0;
        $topic  = str_replace('，',',',safetxt($_POST['topic']));
        $lng    = $_POST['lng'];
        $lat    = $_POST['lat'];
        $competitor= safetxt($_POST['competitor']);
        $addtime= date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);

        $code   = $_POST['area'];
        $s_code=explode('|',$code);
        if($s_code[0]==1||$s_code[0]==2||$s_code[0]==3||$s_code[0]==4
            ||$s_code[0]==32||$s_code[0]==33 ||$s_code[0]==34){
            //32 香港 33 澳门 34 台湾
            $code=$s_code[0].'|1|0';
        }
        //添加区域代码
        $sql="select n_code from pft_area_code_concat where s_code='$code' limit 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $areacode       = $stmt->fetchColumn(0);
        $imgpathGrp     =  safetxt($_POST['imgpathGrp']);
        $lng_lat_pos    = "{$lng},{$lat}";

        if ($update_id) {
            $run_sql = <<<SQL
        UPDATE pft_resource set `title`=?, `p_type`=?, `tel`=?, `jtype`=?, `area`=?,
        `areacode`=?, `address`=?, `runtime`=?, `jtzn`=?, `jdjj`=?, `bhjq`=?, `jqts`=?,
        `imgpathGrp`=?, `verify_status`=?, `topic`=?, `lng_lat_pos`=?,
        `competitor`=?,addtime==? WHERE id=$update_id LIMIT 1
SQL;
        }
        else {
            $run_sql = <<<SQL
        INSERT INTO pft_resource(`title`, `p_type`, `tel`, `jtype`, `area`,
        `areacode`, `address`, `runtime`, `jtzn`, `jdjj`, `bhjq`, `jqts`,
        `imgpathGrp`, `verify_status`, `topic`, `lng_lat_pos`,
        `competitor`,addtime) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
        ?, ?, ?, ?, ?, ?)
SQL;
        }


        $stmt = $this->db->prepare($run_sql);
        return $stmt->execute(
            array(
                $title,$p_type,$tel,$jtype,$address,$runtime,$code,
                $areacode, $address,$runtime,$jtzn,$jdjj,$bhjq,
                $jqts, $imgpathGrp, $verify_status, $topic,
                $lng_lat_pos, $competitor, $addtime
            ));
    }

    public function Set($id, $key, $val)
    {
        $sql = "UPDATE pft_resource SET `$key`=? WHERE id=? LIMIT 1";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute(array($val, $id));
    }

    public function Rm($id)
    {
//        $sql = ""
    }

    public function GetResourceByArea($province, $city)
    {
//        $province = intval($_GET['province']);
//        $city     = intval($_GET['city']);
//        $area = "{$province}|{$city}";
        $sql  = "SELECT id,title FROM pft_resource WHERE area LIKE '{$province}|{$city}%'";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        return $data;
    }


    /**
     * 获取资源详情
     *
     * @param int $id 资源id
     * @return array
     * @throws \ErrorException
     */
    public function GetResourceInfo($id)
    {
        if (!is_numeric($id) || $id<=0) throw new \ErrorException('参数个数错误');
        $sql  = "SELECT * FROM pft_resource WHERE id=$id LIMIT 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $data = $stmt->fetch(\PDO::FETCH_ASSOC);
        if (!$data) throw new \ErrorException('该资源不存在');
        return $data;
    }
} 